dfs and similar greedy math trees *1800

Please click on ads to support us..

C++ Code:

/*বিসমিল্লাহির রাহমানির রাহীম*/
#include<bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1e5 + 5;

int n, m;
int people[N];
int h[N];
vector<int> g[N];
int vis[N];
int totalvis[N];
int totalgood[N];

bool ok = true;

void dfs1(int s) {
  totalvis[s] = people[s];
  vis[s] = 1;
  int sum = 0;
  for(int child : g[s]) {
    if(vis[child] == 0) {
      dfs1(child);
      totalvis[s] += totalvis[child];
      sum += totalgood[child];
    }
  }
  int x = h[s] + totalvis[s];
  if(x % 2 == 0) {}
  else ok = false;
  totalgood[s] = x / 2;
  if(totalgood[s] >= 0 and totalgood[s] <= totalvis[s]) {}
  else ok = false;
  if(sum <= totalgood[s]) {}
  else  ok = false;
}

void solve() {
  cin >> n >> m;
  people[n + 1];
  ok = true;
  for(int i = 1; i <= n; i++) {
    cin >> people[i];
  }
  for(int i = 1; i <= n; i++) {
    cin >> h[i];
  }
  for(int i = 1; i < n; i++) {
    int u, v; cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs1(1);
  if(ok) {
    cout << "YES" << endl;
  }
  else {
    cout << "NO" << endl;
  }
  for(int i = 1; i <= n; i++) {
    g[i].clear();
    vis[i] = 0;
  }
}

int32_t main() {

  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

  int t = 1;
  cin >> t;
  while(t--) {
    solve();
  }
}


Comments

Submit
0 Comments
More Questions

952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word